/*
 * Copyright 2020 www.mytijian.com All right reserved. This software is the
 * confidential and proprietary information of www.mytijian.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with www.mytijian.com.
 */
package com.mytijian.task.httprequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class RestTemplateBuilder {
    private static RestTemplate restTemplate;
    static {
        restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0,new StringHttpMessageConverter(Charset.forName("utf-8")));
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {
                int rawStatusCode = response.getRawStatusCode();
                HttpStatus statusCode = HttpStatus.resolve(rawStatusCode);
                return (statusCode != null ? hasError(statusCode) : hasError(rawStatusCode));
            }

            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
            }
            protected boolean hasError(HttpStatus statusCode) {
                return statusCode.isError();
            }
            protected boolean hasError(int unknownStatusCode) {
                HttpStatus.Series series = HttpStatus.Series.resolve(unknownStatusCode);
                return (series == HttpStatus.Series.CLIENT_ERROR || series == HttpStatus.Series.SERVER_ERROR);
            }
        });

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        //10s
        requestFactory.setConnectTimeout(10 * 1000);
        requestFactory.setReadTimeout(10 * 1000);
        restTemplate.setRequestFactory(requestFactory);
    }
    public static RestTemplate buildRestTemplate() {
        return restTemplate;
    }
}
